﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.Menu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.API.Write.Application.Handler.Menu
{
    /// <summary>
    /// 创建角色的菜单权限请求命令处理类
    /// </summary>
    public class CreateRoleMenuHandler:IRequestHandler<CreateRoleMenuCommand,ApiResult<int>>
    {
        IBaseRepository<RoleMenuModel> roleMenuRep;

        public CreateRoleMenuHandler(IBaseRepository<RoleMenuModel> roleMenuRep)
        {
            this.roleMenuRep = roleMenuRep;
        }

        public Task<ApiResult<int>> Handle(CreateRoleMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();
                var rolemenus = roleMenuRep.GetAll().Where(x => x.RoleId == request.roleId && !x.IsDeleted).ToList();
                foreach (var item in rolemenus)
                {
                    item.IsDeleted = true;
                }

                var rolemenu=new List<RoleMenuModel>();

                foreach (var item in request.menuId)
                {
                    rolemenu.Add(new RoleMenuModel()
                    {
                        RoleId=request.roleId,
                        MenuId=item
                    });
                }

                int r1 = 0;
                int r = 0;

                using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if (rolemenus.Count() > 0)
                    {
                        r = roleMenuRep.UpdateAsync(rolemenus).Result;
                    }
                    if (rolemenu.Count() > 0)
                    {
                        r1 = roleMenuRep.CreateAsync(rolemenu).Result;
                    }
                    tran.Complete();
                }

                if (r1 > 0)
                {
                    res.Msg = "菜单权限分配成功";
                    res.Data = r1;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "菜单权限分配失败";
                    res.Code = ApiEnum.Fail;
                }


                return Task.FromResult(res);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
